const { validationResult } = require('express-validator');
const { User, Video, UserFollow } = require('../models');
const Like = require('../models/Like');
const Favorate = require('../models/Favorate');
const sequelize = require('../config/database');
const bcrypt = require('bcrypt');

class UserController {
  // 获取用户列表（需要管理员权限）
  static async getUserList(req, res) {
    try {
      const { page = 1, limit = 20, role, status } = req.query;
      
      const whereCondition = {};
      if (role) {
        whereCondition.role = role;
      }
      if (status) {
        whereCondition.status = status;
      }
      
      const { count, rows } = await User.findAndCountAll({
        where: whereCondition,
        limit: parseInt(limit),
        offset: (parseInt(page) - 1) * parseInt(limit),
        order: [['createdAt', 'desc']],
        attributes: {
          exclude: ['password', 'passwordResetToken', 'passwordResetExpires']
        }
      });
      
      res.json({
        success: true,
        data: {
          users: rows,
          pagination: {
            total: count,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(count / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取用户列表失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 获取用户详情
  static async getUserDetail(req, res) {
    try {
      const userId = req.params.id === 'me' ? req.user.id : req.params.id;
      
      const user = await User.findByPk(userId, {
        attributes: {
          exclude: ['password', 'passwordResetToken', 'passwordResetExpires']
        }
      });
      
      if (!user) {
        return res.status(404).json({ success: false, message: '用户不存在' });
      }
      
      res.json({ success: true, data: user });
    } catch (error) {
      console.error('获取用户详情失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 更新用户信息（需要用户自己或管理员权限）
  static async updateUser(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ success: false, message: '验证失败', errors: errors.array() });
      }
      
      const userId = req.params.id;
      
      // 检查权限：只能更新自己的信息，或者管理员可以更新任意用户
      if (userId !== req.user.id && req.user.role !== 'admin') {
        return res.status(403).json({ success: false, message: '没有权限更新此用户信息' });
      }
      
      const user = await User.findByPk(userId);
      if (!user) {
        return res.status(404).json({ success: false, message: '用户不存在' });
      }
      
      const { username, email, avatar } = req.body;
      
      // 检查用户名是否已被使用
      if (username && username !== user.username) {
        const existingUser = await User.findOne({ where: { username } });
        if (existingUser) {
          return res.status(400).json({ success: false, message: '用户名已被使用' });
        }
      }
      
      // 检查邮箱是否已被使用
      if (email && email !== user.email) {
        const existingUser = await User.findOne({ where: { email } });
        if (existingUser) {
          return res.status(400).json({ success: false, message: '邮箱已被使用' });
        }
      }
      
      await user.update({
        username,
        email,
        avatar
      });
      
      // 返回更新后的用户信息（不包含敏感字段）
      const updatedUser = await User.findByPk(userId, {
        attributes: {
          exclude: ['password', 'passwordResetToken', 'passwordResetExpires']
        }
      });
      
      res.json({ success: true, message: '用户信息更新成功', data: updatedUser });
    } catch (error) {
      console.error('更新用户信息失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 更新用户密码
  static async updatePassword(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ success: false, message: '验证失败', errors: errors.array() });
      }
      
      const { currentPassword, newPassword } = req.body;
      const user = await User.findByPk(req.user.id);
      
      // 验证当前密码
      const isMatch = await bcrypt.compare(currentPassword, user.password);
      if (!isMatch) {
        return res.status(400).json({ success: false, message: '当前密码错误' });
      }
      
      // 检查密码强度
      if (!User.validatePassword(newPassword)) {
        return res.status(400).json({ 
          success: false, 
          message: '密码必须包含至少8个字符，包括大小写字母、数字和特殊字符' 
        });
      }
      
      // 更新密码
      await user.updatePassword(newPassword);
      
      res.json({ success: true, message: '密码更新成功' });
    } catch (error) {
      console.error('更新密码失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 更新用户状态（需要管理员权限）
  static async updateUserStatus(req, res) {
    try {
      const { status } = req.body;
      
      if (!['active', 'inactive', 'banned'].includes(status)) {
        return res.status(400).json({ success: false, message: '无效的状态值' });
      }
      
      const user = await User.findByPk(req.params.id);
      if (!user) {
        return res.status(404).json({ success: false, message: '用户不存在' });
      }
      
      // 不能禁用自己的管理员账号
      if (user.id === req.user.id && status !== 'active') {
        return res.status(400).json({ success: false, message: '不能禁用自己的账号' });
      }
      
      await user.update({ status });
      
      res.json({ success: true, message: '用户状态更新成功', data: user });
    } catch (error) {
      console.error('更新用户状态失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 更新用户角色（需要管理员权限）
  static async updateUserRole(req, res) {
    try {
      const { role } = req.body;
      
      if (!['user', 'admin'].includes(role)) {
        return res.status(400).json({ success: false, message: '无效的角色值' });
      }
      
      const user = await User.findByPk(req.params.id);
      if (!user) {
        return res.status(404).json({ success: false, message: '用户不存在' });
      }
      
      // 不能修改自己的角色
      if (user.id === req.user.id) {
        return res.status(400).json({ success: false, message: '不能修改自己的角色' });
      }
      
      await user.update({ role });
      
      res.json({ success: true, message: '用户角色更新成功', data: user });
    } catch (error) {
      console.error('更新用户角色失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 删除用户（需要管理员权限）
  static async deleteUser(req, res) {
    try {
      const user = await User.findByPk(req.params.id);
      if (!user) {
        return res.status(404).json({ success: false, message: '用户不存在' });
      }
      
      // 不能删除自己的账号
      if (user.id === req.user.id) {
        return res.status(400).json({ success: false, message: '不能删除自己的账号' });
      }
      
      // 实际项目中可能需要软删除，或者先清理用户相关的数据
      await user.destroy();
      
      res.json({ success: true, message: '用户删除成功' });
    } catch (error) {
      console.error('删除用户失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 获取用户统计信息
  static async getUserStats(req, res) {
    try {
      const userId = req.user.id; // 从认证中间件获取当前用户ID
      
      // 并发查询所有统计数据
      const [videoCount, fanCount, followCount] = await Promise.all([
        // 作品数量：用户发布的视频数
        Video.count({
          where: { user_id: userId, deleted_at: null }
        }),
        // 粉丝数量：有多少用户关注了当前用户 (followed_id = 当前用户ID)
        UserFollow.count({
          where: { followed_id: userId, deleted_at: null }
        }),
        // 关注数量：当前用户关注了多少用户 (follower_id = 当前用户ID)
        UserFollow.count({
          where: { follower_id: userId, deleted_at: null }
        })
      ]);

      return res.json({
        success: true,
        message: '获取用户统计信息成功',
        data: {
          userId,
          videoCount,
          fanCount,
          followCount
        }
      });
    } catch (error) {
      console.error('获取用户统计信息失败:', error);
      return res.status(500).json({
        success: false,
        message: '服务器内部错误',
        error: error.message
      });
    }
  }

  // 获取用户收藏的视频列表
  static async getUserFavorites(req, res) {
    try {
      const userId = req.user.id;
      const { page = 1, limit = 20 } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(limit);

      // 使用SQL直接查询用户收藏的视频详情
      const videos = await sequelize.query(
        `SELECT vd.* 
         FROM videos_detail vd
         INNER JOIN favorate f ON vd.id = f.video_id
         WHERE f.user_id = :userId
         ORDER BY f.created_at DESC
         LIMIT :limit OFFSET :offset`,
        {
          replacements: { userId, limit: parseInt(limit), offset },
          type: sequelize.QueryTypes.SELECT
        }
      );

      // 获取总数
      const [[{ total }]] = await sequelize.query(
        'SELECT COUNT(*) as total FROM favorate WHERE user_id = :userId',
        { replacements: { userId } }
      );

      res.json({
        success: true,
        data: {
          videos,
          pagination: {
            total,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(total / parseInt(limit))
          }
        }
      });
    } catch (error) {
      console.error('获取用户收藏视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 获取用户点赞的视频列表
  static async getUserLikedVideos(req, res) {
    try {
      const userId = req.user.id;
      const { page = 1, limit = 20 } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(limit);

      // 使用SQL直接查询用户点赞的视频详情
      const videos = await sequelize.query(
        `SELECT vd.* 
         FROM videos_detail vd
         INNER JOIN likes l ON vd.id = l.video_id
         WHERE l.user_id = :userId
         ORDER BY l.created_at DESC
         LIMIT :limit OFFSET :offset`,
        {
          replacements: { userId, limit: parseInt(limit), offset },
          type: sequelize.QueryTypes.SELECT
        }
      );

      // 获取总数
      const [[{ total }]] = await sequelize.query(
        'SELECT COUNT(*) as total FROM likes WHERE user_id = :userId',
        { replacements: { userId } }
      );

      res.json({
        success: true,
        data: {
          videos,
          pagination: {
            total,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(total / parseInt(limit))
          }
        }
      });
    } catch (error) {
      console.error('获取用户点赞视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }
  
  /**
   * 获取当前登录用户发布的视频
   * 从token中获取user_id，从视图videos_detail中查询用户发布的视频，分页，每页10个
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async getMyVideos(req, res) {
    try {
      // 从req.user中获取用户ID（通过authenticateJWT中间件验证token后设置）
      const userId = req.user.id;
      
      const { page = 1, limit = 10 } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(limit);
      
      // 使用videos_detail视图查询用户发布的视频
      const results = await sequelize.query(
        `SELECT * FROM videos_detail 
         WHERE user_id = :userId
         AND deleted_at IS NULL
         ORDER BY created_at DESC
         LIMIT :limit OFFSET :offset`,
        {
          replacements: { userId, limit: parseInt(limit), offset },
          type: sequelize.QueryTypes.SELECT
        }
      );
      
      // 获取总数
      const [[{ count }]] = await sequelize.query(
        'SELECT COUNT(*) as count FROM videos_detail WHERE user_id = :userId AND deleted_at IS NULL',
        { replacements: { userId } }
      );
      
      res.json({
        success: true,
        data: {
          videos: results,
          pagination: {
            total: count,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(count / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取用户发布的视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 检查当前用户是否关注了指定视频
  static async checkIfFollowingVideo(req, res) {
    try {
      const userId = req.user.id;
      const videoId = req.params.video_id;
      
      // 验证视频是否存在
      const video = await Video.findByPk(videoId);
      if (!video) {
        return res.status(404).json({ success: false, message: '视频不存在' });
      }
      
      // 由于没有专门的视频关注模型，这里假设使用user_follow表，其中follower_id是用户，followed_id是视频ID
      // 注意：这是一个临时解决方案，实际项目中可能需要创建专门的视频关注模型
      const isFollowing = await UserFollow.count({
        where: {
          follower_id: userId,
          followed_id: videoId
        }
      }) > 0;
      
      res.json({
        success: true,
        data: {
          videoId,
          isFollowing
        }
      });
    } catch (error) {
      console.error('检查是否关注视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 检查当前用户是否点赞了指定视频
  static async checkIfLikedVideo(req, res) {
    try {
      const userId = req.user.id;
      const videoId = req.params.video_id;
      
      // 验证视频是否存在
      const video = await Video.findByPk(videoId);
      if (!video) {
        return res.status(404).json({ success: false, message: '视频不存在' });
      }
      
      const isLiked = await Like.isLiked(userId, videoId);
      
      res.json({
        success: true,
        data: {
          videoId,
          isLiked
        }
      });
    } catch (error) {
      console.error('检查是否点赞视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 检查当前用户是否收藏了指定视频
  static async checkIfFavoritedVideo(req, res) {
    try {
      const userId = req.user.id;
      const videoId = req.params.video_id;
      
      // 验证视频是否存在
      const video = await Video.findByPk(videoId);
      if (!video) {
        return res.status(404).json({ success: false, message: '视频不存在' });
      }
      
      // 直接使用SQL查询检查收藏状态
      const [favorited] = await sequelize.query(
        `SELECT COUNT(*) as count FROM favorate WHERE user_id = :userId AND video_id = :videoId`,
        {
          replacements: { userId, videoId },
          type: sequelize.QueryTypes.SELECT
        }
      );
      const isFavorited = favorited.count > 0;
      
      res.json({
        success: true,
        data: {
          videoId,
          isFavorited
        }
      });
    } catch (error) {
      console.error('检查是否收藏视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 获取指定用户的统计信息（公开接口）
  static async getOtherUserStats(req, res) {
    try {
      const userId = req.params.user_id;
      
      // 验证用户是否存在
      const user = await User.findByPk(userId, {
        attributes: ['id', 'username', 'avatar']
      });
      if (!user) {
        return res.status(404).json({ success: false, message: '用户不存在' });
      }
      
      // 并发查询所有统计数据
      const [videoCount, fanCount, followCount] = await Promise.all([
        // 作品数量：用户发布的视频数
        Video.count({
          where: { user_id: userId, deleted_at: null }
        }),
        // 粉丝数量：有多少用户关注了当前用户
        UserFollow.count({
          where: { followed_id: userId, deleted_at: null }
        }),
        // 关注数量：当前用户关注了多少用户
        UserFollow.count({
          where: { follower_id: userId, deleted_at: null }
        })
      ]);

      return res.json({
        success: true,
        message: '获取用户统计信息成功',
        data: {
          user: {
            id: user.id,
            username: user.username,
            avatar: user.avatar
          },
          stats: {
            videoCount,
            fanCount,
            followCount
          }
        }
      });
    } catch (error) {
      console.error('获取用户统计信息失败:', error);
      return res.status(500).json({
        success: false,
        message: '服务器内部错误',
        error: error.message
      });
    }
  }

  // 获取指定用户的作品列表（公开接口）
  static async getOtherUserVideos(req, res) {
    try {
      const userId = req.params.user_id;
      
      // 验证用户是否存在
      const user = await User.findByPk(userId);
      if (!user) {
        return res.status(404).json({ success: false, message: '用户不存在' });
      }
      
      const { page = 1, limit = 10 } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(limit);
      
      // 使用videos_detail视图查询用户发布的视频
      const results = await sequelize.query(
        `SELECT * FROM videos_detail 
         WHERE user_id = :userId
         AND deleted_at IS NULL
         ORDER BY created_at DESC
         LIMIT :limit OFFSET :offset`,
        {
          replacements: { userId, limit: parseInt(limit), offset },
          type: sequelize.QueryTypes.SELECT
        }
      );
      
      // 获取总数
      const [[{ count }]] = await sequelize.query(
        'SELECT COUNT(*) as count FROM videos_detail WHERE user_id = :userId AND deleted_at IS NULL',
        { replacements: { userId } }
      );
      
      res.json({
        success: true,
        data: {
          videos: results,
          pagination: {
            total: count,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(count / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取用户作品列表失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 获取指定用户的收藏列表（公开接口）
  static async getOtherUserFavorites(req, res) {
    try {
      const userId = req.params.user_id;
      
      // 验证用户是否存在
      const user = await User.findByPk(userId);
      if (!user) {
        return res.status(404).json({ success: false, message: '用户不存在' });
      }
      
      const { page = 1, limit = 20 } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(limit);

      // 使用SQL直接查询用户收藏的视频详情
      const videos = await sequelize.query(
        `SELECT vd.* 
         FROM videos_detail vd
         INNER JOIN favorate f ON vd.id = f.video_id
         WHERE f.user_id = :userId
         ORDER BY f.created_at DESC
         LIMIT :limit OFFSET :offset`,
        {
          replacements: { userId, limit: parseInt(limit), offset },
          type: sequelize.QueryTypes.SELECT
        }
      );

      // 获取总数
      const [[{ total }]] = await sequelize.query(
        'SELECT COUNT(*) as total FROM favorate WHERE user_id = :userId',
        { replacements: { userId } }
      );

      res.json({
        success: true,
        data: {
          videos,
          pagination: {
            total,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(total / parseInt(limit))
          }
        }
      });
    } catch (error) {
      console.error('获取用户收藏列表失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 获取指定用户的点赞列表（公开接口）
  static async getOtherUserLikes(req, res) {
    try {
      const userId = req.params.user_id;
      
      // 验证用户是否存在
      const user = await User.findByPk(userId);
      if (!user) {
        return res.status(404).json({ success: false, message: '用户不存在' });
      }
      
      const { page = 1, limit = 20 } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(limit);

      // 使用SQL直接查询用户点赞的视频详情
      const videos = await sequelize.query(
        `SELECT vd.* 
         FROM videos_detail vd
         INNER JOIN likes l ON vd.id = l.video_id
         WHERE l.user_id = :userId
         ORDER BY l.created_at DESC
         LIMIT :limit OFFSET :offset`,
        {
          replacements: { userId, limit: parseInt(limit), offset },
          type: sequelize.QueryTypes.SELECT
        }
      );

      // 获取总数
      const [[{ total }]] = await sequelize.query(
        'SELECT COUNT(*) as total FROM likes WHERE user_id = :userId',
        { replacements: { userId } }
      );

      res.json({
        success: true,
        data: {
          videos,
          pagination: {
            total,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(total / parseInt(limit))
          }
        }
      });
    } catch (error) {
      console.error('获取用户点赞列表失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }
}

module.exports = UserController;